import 'dart:async';

import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../common/log/xmm_logcat.dart';
import '../../common/sp/xmm_shared_preferences_util.dart';
import '../../global/routes/xmm_routes.dart';
import '../../res/xmm_img.dart';

class XmmGuidePage extends StatefulWidget {
  const XmmGuidePage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return XmmGuidePageState();
  }
}

class XmmGuidePageState extends State<XmmGuidePage> {
  final _controller = PageController();

  Timer? timer;

  @override
  void initState() {
    super.initState();
    XmmSPUtil.set("isFirstOpenApp", false);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      startTimer(2);
    });
  }

  void startTimer(int seconds) {
    timer?.cancel();
    timer = Timer(Duration(seconds: seconds), () {
      var page = _controller.page ?? 0;
      if (page.round() < 2) {
        _controller.nextPage(
          duration: const Duration(milliseconds: 300),
          curve: Curves.ease,
        );
      } else {
        Get.offAllNamed(XmmRoutes.loginPage);
      }
    });
  }

  void cancelTimer() {
    XmmXLogcat.d("cancelTimer");
    timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NotificationListener(
        onNotification: (notification) {
          if (notification is ScrollStartNotification) {
            cancelTimer();
          } else if (notification is ScrollEndNotification) {
            startTimer(2);
          }
          return false;
        },
        child: PageView(
          scrollDirection: Axis.horizontal,
          reverse: false,
          controller: _controller,
          children: [
            Image.asset(XmmImg.splashGuide1),
            Image.asset(XmmImg.splashGuide2),
            Image.asset(XmmImg.splashGuide3)
          ],
          onPageChanged: (index) {},
        ),
      ),
    );
  }
}
